﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using JBeamLibrary.VehicleParts;
using JBeamLibrary.VehicleParts.Elements;

namespace DriveBeamEditor.Controls.BeamNG.Controls
{
    public partial class SlotSelectionControl : VehicleControl
    {
        #region Fields

        public event EventHandler<Slot> SelectedSlotChanged;
        public event EventHandler<Slot> SlotValidated;

        #endregion

        #region Properties

        /// <summary>Gets the selected vehicle part</summary>
        public VehiclePart SelectedVehiclePart
        {
            get { return bindingSourceParts.Current as VehiclePart; }
        }

        /// <summary>Gets the selected slot</summary>
        public Slot SelectedSlot
        {
            get { return bindingSourceSlots.Current as Slot; }
        }

        #endregion

        #region CTORs

        public SlotSelectionControl()
        {
            InitializeComponent();
        }

        #endregion

        #region Events

        private void bindingSourceParts_CurrentChanged(object sender, EventArgs e)
        {
            BindSlots();
        }

        private void bindingSourceSlots_CurrentChanged(object sender, EventArgs e)
        {
            if (SelectedSlotChanged != null)
                SelectedSlotChanged(this, SelectedSlot);
        }

        private void gridSlots_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (SlotValidated != null)
                SlotValidated(this, SelectedSlot);
        }

        #endregion

        #region Methods

        private void BindParts()
        {
            gridParts.Enabled = false;
            bindingSourceParts.DataSource = null;

            if (Vehicle != null)
                bindingSourceParts.DataSource = Vehicle.AllParts;

            gridParts.Refresh();
            gridParts.Enabled = true;
        }

        private void BindSlots()
        {
            gridSlots.Enabled = false;
            bindingSourceSlots.DataSource = null;

            if (SelectedVehiclePart != null)
                bindingSourceSlots.DataSource = SelectedVehiclePart.Slots;

            gridSlots.Refresh();
            gridSlots.Enabled = true;
        }

        protected override void BindVehicle()
        {
            BindParts();
            base.BindVehicle();
        }

        public void Reload()
        {
            bindingSourceParts.ResetBindings(false);
            bindingSourceSlots.ResetBindings(false);
        }

        #endregion
    }
}
